package com.test.clyq.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.cplatform.util2.FileTools;
import com.cplatform.util2.TimeStamp;
import com.test.Constants;
import com.test.clyq.entity.RegisterUser;
import com.test.clyq.entity.Users;
import com.test.clyq.entity.UsersLog;
import com.test.clyq.form.RegisterUserForm;
import com.test.clyq.service.RegisterUsersService;
import com.test.clyq.service.UserService;
import com.test.clyq.service.UsersLogService;
import com.test.json.JsonUtil;
import com.test.util.DateUtils;
import com.test.util.FormatExceptionStack;
import com.test.util.ItemUtil;
import com.test.util.Pagination;
import com.test.util.SessionUtil;
import com.test.util.UploadFileUtil;
import com.test.webapp.action.BaseAction;

/**
 * RegisterUserAction. <br>
 * 注册用户管理.
 * <p>
 * Copyright: Copyright (c) 2012-2-24 下午04:51:40
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: liuxl@c-platform.com
 * <p>
 * Version: 1.0
 * <p>
 */
public class RegisterUserAction extends BaseAction {

	/**
	 * login
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return pingBack
	 * @throws IOException
	 */
	public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String pwd = request.getParameter("pwd");
		String uName = request.getParameter("name");
		String rand = request.getParameter("checkCode");
		String sRand = (String) request.getSession().getAttribute("rand");
		UsersLogService usersLogService = (UsersLogService) getBean("usersLogService");
		StringBuilder sb = new StringBuilder();
		sb.append("{success:true,");
		if (!rand.equals(sRand)) {
			sb.append("message:'noRand'");
			sb.append("}");
			print(response, sb.toString(), null, null);
			return null;
		}
		UserService userService = (UserService) getBean("userService");
		try {
			pwd = DigestUtils.md5Hex(pwd);
			Users user = userService.getUsersByNameAndPwd(uName, pwd);
			if (user != null) {
				SessionUtil.setSession(request, user);
				UsersLog userLog = new UsersLog();
				userLog.setOperateTime(Long.valueOf(System.currentTimeMillis()));
				userLog.setUsedTime(Long.valueOf(1000L));
				userLog.setUsersId(user.getId());
				userLog.setUsersLoginName(user.getUsersLoginName());
				userLog.setOperateType(Long.valueOf(3L));
				userLog.setOperateDataType(Long.valueOf(5L));
				userLog.setOperateStatus(Long.valueOf(1L));
				userLog.setOperateTableKey(user.getId());
				userLog.setBeforeOperateData(null);
				userLog.setAfterOperateData((new StringBuilder(String.valueOf(user.getUsersLoginName()))).append(" 在  ")
				        .append(DateUtils.longToDateString(Long.valueOf(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss 登录系统!")).append("登录IP为：")
				        .append(request.getRemoteAddr()).toString());
				usersLogService.addUsersLog(userLog);
				sb.append("message:'logon'");
				sb.append("}");
				print(response, sb.toString(), null, null);
			} else {
				sb.append("message:'logoError'");
				sb.append("}");
				print(response, sb.toString(), null, null);
			}
		}
		catch (Exception e) {
			log.error((new StringBuilder("login:失败 ")).append(FormatExceptionStack.formatException(e)).toString());
			sb.append("message:'logoError'");
			sb.append("}");
			print(response, sb.toString(), null, null);
		}
		return null;
	}

	/**
	 * loginOut
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return pingBack
	 * @throws IOException
	 */
	public ActionForward loginOut(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		Users user = SessionUtil.getUserFromSession(request);
		UsersLogService usersLogService = (UsersLogService) getBean("usersLogService");
		try {
			UsersLog userLog = new UsersLog();
			userLog.setOperateTime(System.currentTimeMillis());
			userLog.setUsedTime(1000l);
			userLog.setUsersId(user.getId());
			userLog.setUsersLoginName(user.getUsersLoginName());
			userLog.setOperateType(Long.valueOf(ItemUtil.LOGINOUT));
			userLog.setOperateDataType(5l);
			userLog.setOperateStatus(1l);
			userLog.setOperateTableKey(user.getId());
			userLog.setBeforeOperateData(null);
			userLog.setAfterOperateData(user.getUsersLoginName() + " 在  "
			        + DateUtils.longToDateString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss" + " 退出系统!"));
			usersLogService.addUsersLog(userLog);
			request.getSession().setAttribute("user", null);
			request.getSession().setAttribute("webSiteName", null);
			SessionUtil.destroySession(request);
			print(response, true);
			return null;
		}
		catch (Exception e) {
			this.log.error("login:失败 " + FormatExceptionStack.formatException(e));
			request.setAttribute("HtmlError", "对不起，系统服务器忙，请您稍候再试.");
			return mapping.findForward("error");
		}
	}

	/**
	 * 保存zip文件
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward saveTxt(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException {

		RegisterUserForm websiteFileForm = (RegisterUserForm) form;
		RegisterUsersService userService = (RegisterUsersService) getBean("registerUsersService");
		try {
			String fileCacheDir = Constants.REGISTER_USER_FILE_DIR;
			UploadFileUtil.UpFile(websiteFileForm.getFile(), fileCacheDir, "txt", 0, true);
			String fileDir = fileCacheDir + websiteFileForm.getFile().getFileName();
			List<String> phoneList = FileTools.readLines(fileDir);
			if (phoneList != null && !phoneList.isEmpty()) {
				for (String obj : phoneList) {
					RegisterUser user = new RegisterUser();
					user.setUsersName(obj);
					user.setUsersPhone(obj);
					user.setUsersPassword(DigestUtils.md5Hex(Constants.DEFAULT_PASSWORD));
					user.setCreateTime(TimeStamp.getTime(TimeStamp.YYYYMMDDhhmmss));
					userService.saveOrUpdate(user);
				}
			}
			StringBuilder sb = new StringBuilder();
			sb.append("{");
			sb.append("success:true");
			sb.append("}");
			String dd = sb.toString();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html; charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(dd);
		}
		catch (Exception e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
			StringBuilder sb = new StringBuilder();
			sb.append("{");
			sb.append("success:false");
			sb.append("}");
			String dd = sb.toString();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html; charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(dd);
		}
		// System.out.println( upPath );

		log.debug("保存文件成功");
		log.info("保存文件end");

		return null;

	}

	/**
	 * 保存用户
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward saveUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("保存用户start");
		RegisterUser user = new RegisterUser();
		String uName = request.getParameter("usersName");
		String password = request.getParameter("usersPassword");
		String email = request.getParameter("usersEmail");
		String desc = request.getParameter("usersDesc");
		String phone = request.getParameter("usersPhone");
		RegisterUsersService userService = (RegisterUsersService) getBean("registerUsersService");
		try {
			user.setUsersDesc(desc);
			user.setUsersName(uName);
			user.setUsersEmail(email);
			user.setUsersPhone(phone);
			user.setUsersPassword(DigestUtils.md5Hex(password));
			user.setCreateTime(TimeStamp.getTime(TimeStamp.YYYYMMDDhhmmss));
			userService.saveOrUpdate(user);
			this.log.debug("保存用户成功");
			this.log.info("保存用户end");
			print(response, true);
		}
		catch (Exception e) {
			this.log.error("保存用户:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}

	/**
	 * 更新用户
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward updateUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("更新用户start");
		String uName = request.getParameter("usersLoginName");
		String fullName = request.getParameter("usersFullName");
		String email = request.getParameter("usersEmail");
		String desc = request.getParameter("usersDesc");
		String phone = request.getParameter("usersPhone");
		String mobile = request.getParameter("usersMobile");
		String address = request.getParameter("usersAddress");
		String password = request.getParameter("password");
		String uId = request.getParameter("usersId");
		UserService userService = (UserService) getBean("userService");
		try {
			Users user = userService.getUsersById(Long.valueOf(uId));
			user.setUsersAddress(address);
			user.setUsersDesc(desc);
			user.setUsersLoginName(uName);
			user.setUsersEmail(email);
			user.setUsersMobile(mobile);
			user.setUsersPhone(phone);
			// user.setIsUsersAdmin(Long.valueOf(0));
			user.setUsersFullName(fullName);
			if ((password != null) && (!"".equals(password))) {
				user.setUsersPassword(DigestUtils.md5Hex(password));
			}
			userService.saveOrUpdate(user);
			this.log.debug("更新用户成功");
			this.log.info("更新用户end");
			print(response, true);
		}
		catch (Exception e) {
			this.log.error("保存用户:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}

	/**
	 * 获得用户列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return 用户列表
	 * @throws IOException
	 */
	public ActionForward userList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("获得用户列表start");
		RegisterUsersService userService = (RegisterUsersService) getBean("registerUsersService");
		try {
			Pagination pagination = new Pagination(1, 100);// 设置分页参数（页码和每页显示记录条数）
			List<RegisterUser> list = null;
			list = userService.userList(pagination); // 获取用户列表
			String jsonStr = JsonUtil.getJsonStr(list, null, -1);
			this.log.debug("获得用户列表成功");
			this.log.info("获得用户列表end");
			print(response, jsonStr, null, null);
		}
		catch (Exception e) {
			this.log.error("获得用户:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}
}
